﻿using GLB.Global;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace _17bangMVC.Controllers
{
    public class CaptchaController : Controller
    {
        // GET: Captcha
        public ActionResult Get()
        {
            int height = 30, weight = 80;
            Bitmap image = new Bitmap(weight, height);  //生成一个像素图“画板”
            Random random = new Random();

            Graphics g = Graphics.FromImage(image);    //在画板的基础上生成一个绘图对象
            g.Clear(Color.FromArgb(random.Next(20), random.Next(150), random.Next(150), random.Next(150)));

            for (int i = 0; i < 20; i++)
            {
                int startX = random.Next(height / 2),
                    startY = random.Next(height),
                    endX = random.Next(startX, weight),
                    endY = random.Next(height / 2);
                g.DrawLine(
                    new Pen(Color.FromArgb(
                        random.Next(255),
                        random.Next(255),
                        random.Next(255),
                        random.Next(255))),
                    new Point(startX, startY),
                    new Point(endX, endY)
                    ); //画直线
            }

            string word = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 4; i++)
            {
                int index = random.Next(word.Length);
                sb.Append(word[index]);
            }
            string captchar = sb.ToString();
            Session[Keys.Captcha] = captchar;

            g.DrawString(captchar,    //绘制字符串 
                      new Font("Corbel Light", 15),                //指定字体
                      new SolidBrush(Color.FromArgb(random.Next(200), random.Next(200), random.Next(200))),      //绘制时使用的刷子
                      new PointF(10, 5)
                      );//左上角定位
            for (int i = 0; i < 80; i++)
            {
                image.SetPixel(random.Next(weight), random.Next(height), Color.FromArgb(random.Next(97), random.Next(97), random.Next(97)));  //绘制一个像素的点

            }

            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Png);

            return File(stream.ToArray(), "image/png");
        }
    }
}